<?php
namespace app\api\service;
use think\Controller;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/26 0026
 * Time: 15:40
 */

class Upload extends Controller {

    /**
     * 图片上传接口
     * @return mixed
     */
    public static function upload_image() {
        // 获取表单上传文件 例如上传了001.jpg
        $files = request()->file('image');
        $type = input('param.image_type', 'images');
        try {
            $paths = [];
            if (is_array($files)) {
                foreach($files as $file){
                    // 移动到框架应用根目录/public/uploads/ 目录下
                    $info = $file->validate(['size'=>2097152,'ext'=>'jpg,jpeg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $type);
                    if($info){
                        $paths[] = 'uploads' . DS . $type . DS . $info->getSaveName();
                    }else{
                        // 上传失败获取错误信息
                        throw new \Exception($file->getError());
                    }
                }
            }else {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $files->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $type);
                if($info){
                    // 成功上传后 获取上传信息
                    $paths[] = 'uploads' . DS . $type . DS . $info->getSaveName();
                }else{
                    // 上传失败获取错误信息
                    return json(['code' => 0, 'msg' => $files->getError()]);
                }
            }
            $thumb_images = [];
            foreach ($paths as $path) {
                $image = \think\Image::open($path);
                $ext = substr($path, strrpos($path, '.'));
                $thumb_path =  str_replace($ext, '-thumb' . $ext, $path);
                if ($type == 'banner') {
                    $image->thumb(750, 430)->save($thumb_path);
                } else if ($type == 'category1') {
                    $image->thumb(750, 255)->save($thumb_path);
                } else if ($type == 'category3') {
                    $image->thumb(320, 380)->save($thumb_path);
                } else {
                    $image->thumb(375, 375)->save($thumb_path);
                }
                $thumb_images[] = [
                    'path' => $path,
                    'thumb_path' => $thumb_path,
                    'host_path' => get_img_url($thumb_path)
                ];
            }
            return ['code' => 200, 'data' => $thumb_images, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
}